using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;

public class EyebrowMaskRenderFeature : ScriptableRendererFeature
{
    [System.Serializable]
    public class EyebrowMaskSettings
    {
        public RenderPassEvent renderPassEvent = RenderPassEvent.AfterRenderingOpaques;
        
        [Tooltip("面部模型对象名（场景里的GameObject名称）")]
        public string faceModelName = "吟霖1.05_mesh";
        
        [Tooltip("使用的面部材质索引")]
        public int faceMaterialIndex = 7;
        
        [Tooltip("ID贴图在材质中的属性名")]
        public string idMapPropertyName = "_IDMap";
        
        [Tooltip("是否反转输出的遮罩")]
        public bool invertMask = false;

        [Range(0f, 1f)]
        [Tooltip("眉毛区域阈值(ID图R通道小于此值的区域会被视为眉毛)")]
        public float eyebrowThreshold = 0.1f;
        
        [Range(0f, 1f)]
        [Tooltip("眉毛遮罩强度")]
        public float eyebrowMaskStrength = 1.0f;
    }

    public EyebrowMaskSettings settings = new EyebrowMaskSettings();
    private EyebrowMaskRenderPass renderPass;

    public override void Create()
    {
        renderPass = new EyebrowMaskRenderPass(settings);
    }

    public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
    {
        if (renderPass.SetupRT(ref renderingData))
        {
            Shader.SetGlobalTexture("_EyebrowMaskTexture", renderPass.GetCurrentRT());
            renderer.EnqueuePass(renderPass);
        }
    }

    protected override void Dispose(bool disposing)
    {
        renderPass?.Dispose();
        base.Dispose(disposing);
    }

    class EyebrowMaskRenderPass : ScriptableRenderPass
    {
        private EyebrowMaskSettings settings;
        private RenderTexture targetRT;
        private Material faceMaskMaterial;
        private ProfilingSampler profilingSampler;

        public EyebrowMaskRenderPass(EyebrowMaskSettings settings)
        {
            this.settings = settings;
            renderPassEvent = settings.renderPassEvent;
            profilingSampler = new ProfilingSampler("EyebrowMaskCapture");
            
            // 仅创建遮罩反转材质（如果需要的话）
            if (settings.invertMask)
            {
                Shader invertShader = Shader.Find("Hidden/InvertTexture");
                if (invertShader != null)
                {
                    faceMaskMaterial = new Material(invertShader);
                }
                else
                {
                    Debug.LogWarning("无法找到InvertTexture着色器,遮罩反转功能将不可用");
                }
            }
        }

        public void Dispose()
        {
            if (targetRT != null)
            {
                targetRT.Release();
                targetRT = null;
            }
            
            if (faceMaskMaterial != null)
            {
                Object.DestroyImmediate(faceMaskMaterial);
                faceMaskMaterial = null;
            }
        }

        public bool SetupRT(ref RenderingData renderingData)
        {
            var desc = renderingData.cameraData.cameraTargetDescriptor;
            desc.depthBufferBits = 0;
            desc.msaaSamples = 1;
            desc.width = Mathf.Max(1, desc.width / 2);
            desc.height = Mathf.Max(1, desc.height / 2);
            desc.sRGB = false;
            desc.colorFormat = RenderTextureFormat.ARGB32;

            if (targetRT == null || targetRT.width != desc.width || targetRT.height != desc.height || targetRT.format != desc.colorFormat)
            {
                if (targetRT != null) targetRT.Release();
                targetRT = new RenderTexture(desc);
                targetRT.name = "EyebrowMaskRT_Internal";
                if (!targetRT.Create())
                {
                    Debug.LogError("EyebrowMaskRT 创建失败!");
                    targetRT = null;
                    return false;
                }
            }
            return targetRT != null;
        }

        public RenderTexture GetCurrentRT()
        {
            return targetRT;
        }

        public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
        {
            GameObject faceModel = GameObject.Find(settings.faceModelName);
            if (faceModel == null)
            {
                Debug.LogWarning($"未找到名为 {settings.faceModelName} 的面部模型对象");
                return;
            }

            Renderer faceRenderer = faceModel.GetComponent<Renderer>();
            if (faceRenderer == null || faceRenderer.sharedMaterials.Length <= settings.faceMaterialIndex)
            {
                Debug.LogWarning("找不到有效的面部渲染器或材质");
                return;
            }

            Material faceMaterial = faceRenderer.sharedMaterials[settings.faceMaterialIndex];
            if (faceMaterial == null)
            {
                Debug.LogWarning("面部材质为空");
                return;
            }

            // 检查材质是否包含ID贴图
            if (!faceMaterial.HasProperty(settings.idMapPropertyName))
            {
                Debug.LogWarning($"面部材质不包含ID贴图属性 {settings.idMapPropertyName}");
                return;
            }

            // 设置或启用面部材质的眉毛遮罩输出关键字
            faceMaterial.EnableKeyword("_OUTPUT_EYEBROW_MASK");
            
            // 设置眉毛遮罩强度
            if (faceMaterial.HasProperty("_EyebrowMaskStrength"))
            {
                faceMaterial.SetFloat("_EyebrowMaskStrength", settings.eyebrowMaskStrength);
            }

            CommandBuffer cmd = CommandBufferPool.Get("EyebrowMaskCapture");

            using (new ProfilingScope(cmd, profilingSampler))
            {
                cmd.SetRenderTarget(targetRT);
                cmd.ClearRenderTarget(true, true, Color.black);

                // 直接使用面部材质的第二个Pass(索引为1, 名为"EyebrowMaskOutput")渲染到RT
                cmd.DrawRenderer(faceRenderer, faceMaterial, settings.faceMaterialIndex, 1);
                Debug.Log($"Drawing {faceRenderer.name} with ToonBody shader, materialIndex: {settings.faceMaterialIndex}, passIndex: 1 (EyebrowMaskOutput)");

                // 根据需要反转遮罩
                if (settings.invertMask && faceMaskMaterial != null)
                {
                    RenderTexture tempRT = RenderTexture.GetTemporary(targetRT.width, targetRT.height, 0, targetRT.format);
                    cmd.Blit(targetRT, tempRT);
                    cmd.Blit(tempRT, targetRT, faceMaskMaterial);
                    cmd.ReleaseTemporaryRT(Shader.PropertyToID(tempRT.name));
                }

                context.ExecuteCommandBuffer(cmd);
                cmd.Clear();
            }

            // 绘制完成后禁用关键字，不影响正常渲染
            faceMaterial.DisableKeyword("_OUTPUT_EYEBROW_MASK");

            CommandBufferPool.Release(cmd);
        }
    }
}